<template>
  <div class="content-box">
    <el-form
      ref="flowFormRef"
      :model="flowFormData"
      :rules="fromRules"
      label-width="180px"
      class="form__content"
    >
      <template v-if="true">
        <el-form-item label="审批意见" prop="approval">
          <el-radio-group v-model="flowFormData.approval">
            <el-radio label="1">同意</el-radio>
            <el-radio label="0">不同意</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="检验拍照" prop="approvalImgs">
          <ecm-image-upload
            :disabled="!isEdit"
            :files="flowFormData.approvalImgs"
            @set-file="
              fileList => {
                handleChange(fileList);
              }
            "
          ></ecm-image-upload>
        </el-form-item>
        <el-form-item label="备注" prop="approvalRemark">
          <el-input
            :disabled="!isEdit"
            type="textarea"
            :rows="4"
            placeholder="请输入内容"
            v-model="flowFormData.approvalRemark"
          ></el-input>
        </el-form-item>
      </template>
    </el-form>

    <div class="form__footer right-align-box" v-if="isEdit">
      <el-button @click="handleBack">取 消</el-button>
      <el-button
        type="primary"
        @click="handleTransfer"
        v-if="nodeDefId !== 'ACT_010'"
        >转 办</el-button
      >
      <el-button
        type="danger"
        @click="handleReject"
        v-if="nodeDefId !== 'ACT_010'"
        >驳 回</el-button
      >
      <el-button type="primary" @click="handleSave">保 存</el-button>
      <el-button type="primary" @click="handleSubmit()">提 交</el-button>
    </div>

    <el-dialog
      title="选择【建设单位主管副组长】"
      v-model="dialogVisibleTransferAdd"
      width="920px"
    >
      <add-user
        v-model:dialogVisibleTransferAdd="dialogVisibleTransferAdd"
        :currentUsers="acceptUsers"
        :isSingle="true"
        :only-inset="true"
        @emitAddUser="showNextJump"
      />
    </el-dialog>

    <el-dialog
      title="驳回"
      v-model="dialogVisible"
      destroy-on-close
      width="600px"
    >
      <reject-view
        v-model:dialogVisible="dialogVisible"
        :taskId="formBaseInfo.taskId"
        :formBaseInfo="formBaseInfo"
        :module="module"
      />
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import { defineProps, watch, ref, defineEmits, watchEffect } from "vue";
import { useRoute } from "vue-router";
import AddUser from "../../../projectsA/acceptance/concealed/components/dialog/AddUser.vue";
import RejectView from "../dialog/RejectView.vue";
import { storageLocal } from "/@/utils/storage";
import { snapUpdate, snapFlowSubmit } from "/@/api/construction";
import { approvalAccess } from "/@/api/vehicle"
// import { flowNotify } from "/@/api/work";
import {
  // projectTeamList,
  // getApproveHandlerId,
  transfer,
  postSaveDraft,
  getDraft
} from "/@/api/projects";
import { flowTypeObj } from "../../detail/type";
import NotifMessage from "/@/utils/message/notification";
import { onFilterFileData, onInitFileList } from "/@/utils/file";
import ecmImageUpload from "/@/components/ecmImage/index.vue";
import ecmUpload from "/@/components/ecmUpload/index.vue";
const route = useRoute();
const flowFormRef = ref<HTMLFormElement | null>(null) as any;
const rejectFormRef = ref<HTMLFormElement | null>(null) as any;
const emit = defineEmits(["handleSubmit", "handleBack"]);
const props = defineProps({
  formBaseInfo: {
    type: Object,
    default: () => {}
  },
  module: {
    type: String,
    default: "snap"
  }
});
const formBaseInfo = ref<object>({});
const initVal = ref(true);
const flowFormData = ref({
  // snapshotName: formBaseInfo.value.snapshotName || "",
  // content: formBaseInfo.value.content || "",
  // snapshotAttachment: formBaseInfo.value.snapshotAttachment || [],
  // rectificationAttachment: [],
  partybHandlerInfo: [] as any,
  partybHandlerId: "",
  partybHandlerName: "",
  // rectificationInfo: "",
  defaultFileList: [],
  // supervisorAccOpinion: "",
  option: [],
  approval: '', // 是否审批通过
  approvalImgs: [], // 检验拍照
  approvalRemark: [] // 备注
}); // 待处理信息

const fromRules = ref({
  approval: [
    { required: true, message: "请选择审批意见", trigger: "change" }
  ]
  // approvalImgs: [
  //   { required: true, message: "请上传照片", trigger: "change" }
  // ],
  // approvalRemark: [
  //   { required: true, message: "请输入备注", trigger: "change" }
  // ],

  // 其他表单内容先注释
  // rectificationAttachment: [
  //   { required: true, message: "请上传整改说明", trigger: "change" }
  // ],
  // rectificationInfo: [
  //   { required: true, message: "请填写整改说明", trigger: "change" }
  // ],
  // supervisorAccOpinion: [
  //   { required: true, message: "请输入审批意见", trigger: "change" }
  // ],
  // snapshotName: [
  //   { required: true, message: "请填写问题标题", trigger: "change" }
  // ],
  // content: [{ required: true, message: "请填写问题内容", trigger: "change" }],
  // snapshotAttachment: [
  //   { required: true, message: "请上传照片", trigger: "change" }
  // ]
});
const dialogVisible = ref(false); // 驳回弹窗是否展示
const dialogVisibleTransferAdd = ref(false); // 选择人员的弹窗是否显示
let dialogVisibleType = ref("submit");
const acceptUsers = ref([]); // 已选择人员
const addUserInfo = ref<object>({}); // 人员选择器，所选择人员信息
const isEdit = ref(route.query?.mode !== "read");
const nodeDefId = ref(route.query?.nodeDefId);
const instanceId = ref(route.query?.instanceId);
const flowId = ref(route.query?.flowId);
const flowType = ref(route.query?.flowType);
const lastNode = ref("");
// const approveHandlerId = ref("");
const nodeList = flowTypeObj[flowType.value].nodeId;
lastNode.value = nodeList[nodeList.length - 1];

const handleChange = (fileList) => {
    flowFormData.value.approvalImgs = fileList;
    flowFormRef.value.clearValidate("approvalImgs");
};

//转办
const handleTransfer = async () => {
  dialogVisibleTransferAdd.value = true;
  dialogVisibleType.value = "transfer";
};

// 提交(最后一个节点驳回)
const handleSubmit = async () => {
  let nodes = flowTypeObj[flowType.value].nodeId;
  if (nodeDefId.value === nodes[nodes.length - 1] || flowFormData.value.approval === '0') {
    const isValid = await new Promise(resolve =>
      flowFormRef.value.validate(resolve)
    );
    if (!isValid) return;
    emitAddUser();
  } else {
    const isValid = await new Promise(resolve =>
      flowFormRef.value.validate(resolve)
    );
    if (!isValid) return;
    dialogVisibleTransferAdd.value = true;
    dialogVisibleType.value = "submit";
  }
};

const showNextJump = parmas => {
  addUserInfo.value = parmas;
  if (dialogVisibleType.value === "submit") {
    emitAddUser();
  } else if (dialogVisibleType.value === "transfer") {
    //转办
    submitTransfer(parmas);
  }
};

const handleSave = async () => {
  const params = {
    flowId: flowId.value,
    nodeId: nodeDefId.value,
    taskId:formBaseInfo.value?.taskId,
    formJson: JSON.stringify(flowFormData.value)
  };
  const { code, message } = await postSaveDraft(params);
  if (code === 200) {
    NotifMessage.success(message);
  } else {
    NotifMessage.error(message);
  }
}

const getFlowFormData = async () => {
  const { data } = await getDraft(formBaseInfo.value?.taskId);
  if (data?.formJson) {
    flowFormData.value = JSON.parse(data.formJson);
  }
}

const emitAddUser = () => {
  dialogVisibleTransferAdd.value = false;
  submitApproval();
};

const submitApproval = async () => {
  let nextHandleId = "";
  const info = storageLocal.getItem("info");
  if (lastNode.value === nodeDefId.value) {
    //最后一个节点
    nextHandleId = info?.userId;
  } else {
    nextHandleId = addUserInfo.value?.idList && addUserInfo.value?.idList[0]?.id;
  }
  let { approvalImgs, approvalRemark } = flowFormData.value;
  formBaseInfo.value.option = [
    {
      name: "检验拍照",
      content: approvalImgs,
      type: "images"
    },
    { name: "备注", content: approvalRemark, type: "textarea" }
  ];
  const params = {
    formBaseInfo: {
      id: formBaseInfo.value.id,
      acceptUsers: nextHandleId
    },
    flowFormData: {
      businessId: formBaseInfo.value.id,
      flowId: flowId.value,
      flowTypeCode: formBaseInfo.value?.flowMinType || flowType.value,
      instanceId: instanceId.value,
      nodeId: nodeDefId.value,
      projectManageId: storageLocal.getItem("projectInfo")?.id
    },

    formSubMap: {
      flowType: formBaseInfo.value?.flowMinType || flowType.value,
      nodeId: nodeDefId.value,
      procInstId: instanceId.value,
      taskId: formBaseInfo.value?.taskId,
      opinion: JSON.stringify(formBaseInfo.value.option),
      assignee: nextHandleId,
      approval: flowFormData.value.approval
    },

    tmpStorage: {
      nodeId: nodeDefId.value,
      flowId: flowId.value,
      taskId: formBaseInfo.value?.taskId,
      handlerId: nextHandleId,
      userId: info ? info?.userId : "",
      valueJson: JSON.stringify(flowFormData.value)
    }
  }
  const { code, message } = await approvalAccess(params);
  if (code === 200) {
    NotifMessage.success(message);
    emit("handleBack");
  } else {
    NotifMessage.error(message);
  }
}

const submitTransfer = async parmas => {
  const info = storageLocal.getItem("info");
  const option = [{ name: "转办", content: "转办协助处理", type: "textarea" }];
  let params = {
    targetAssignee: parmas?.idList[0].id,
    opinion: JSON.stringify(option),
    instanceId: instanceId.value,
    taskId: formBaseInfo.value?.taskId,
    flowId: flowId.value,
    handlerId: info?.userId,
    handlerName: info?.name,
    businessTraParam: {
      id: formBaseInfo.value.id,
      acceptUsers: info?.userId,
      flowType: formBaseInfo.value?.flowMinType || flowType.value
    }
  };
  try {
    const { code, message } = await transfer(params);
    if (code === 200) {
      // try {
      //   _czc.push([
      //     "_trackEvent",
      //     "其他问题（随手拍）审批详情",
      //     "转办",
      //     `${formBaseInfo.value.billName}_${formBaseInfo.value?.flowMinType}`
      //   ]);
      // } catch (err) {
      //   console.log(err);
      // }
      NotifMessage.success(message);
      emit("handleBack");
    } else {
      NotifMessage.error(message);
    }
  } catch (err) {
    console.log(err);
  }
};

const handleReject = () => {
  dialogVisible.value = true;
};

const handleBack = () => {
  emit("handleBack");
};
watchEffect(() => {
  if (formBaseInfo.value?.taskId) {
    getFlowFormData();
  }
})
watch(
  () => props.formBaseInfo,
  newVal => {
      formBaseInfo.value = newVal;
      // let { snapshotName, content, snapshotAttachment } = newVal;
      // if (initVal.value) {
      //   flowFormData.value.snapshotName = snapshotName;
      //   flowFormData.value.content = content;
      //   flowFormData.value.snapshotAttachment =
      //     onInitFileList(snapshotAttachment);
      //   initVal.value = false;
      // }
      // if (!isEdit.value) {
      //   flowFormData.value.rectificationAttachment =
      //     newVal.rectificationAttachment;
      // }
  },
  {
    deep: true,
    immediate: true
  }
);
</script>

<style lang="scss" scoped>
.next-content {
  padding: 10px 20px;
}

:deep(.form__content) {
  .el-form-item--small.el-form-item {
    margin-bottom: 18px;
  }
}
</style>
